<script setup>
import { ref, onUnmounted, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const tags = ref([])

// 用于存储标签的集合，避免重复
const visitedTags = new Set()

// 监听路由变化
watch(route, (newRoute) => {
  // 检查当前路由是否已经有对应的标签
  if (!visitedTags.has(newRoute.name)) {
    const tag = {
      path: newRoute.path,
      name: newRoute.name,
      title: newRoute.meta.title || 'Untitled',
      closable: newRoute.matched.length !== 1 // 最后一个标签不可关闭
    }
    tags.value.push(tag)
    visitedTags.add(newRoute.name)
  }
})

// 关闭标签
function handleClose(tag) {
  const index = tags.value.indexOf(tag)
  if (index > -1) {
    tags.value.splice(index, 1)
    visitedTags.delete(tag.name)
    // 如果关闭的不是最后一个标签，则导航到前一个标签
    if (index > 0) {
      router.push(tags.value[index - 1].path)
    } else if (tags.value.length > 0) {
      // 如果关闭的是第一个标签，导航到最后一个标签
      router.push(tags.value[tags.value.length - 1].path)
    }
  }
}

// 组件卸载时清除
onUnmounted(() => {
  // 清除所有相关资源，例如定时器或事件监听器
})

// 初始化标签
onMounted(() => {
  if (route.matched.length > 0 && !visitedTags.has(route.name)) {
    const initialTag = {
      path: route.path,
      name: route.name,
      title: route.meta.title || 'Default Title',
      closable: route.matched.length !== 1
    }
    tags.value.push(initialTag)
    visitedTags.add(route.name)
  }
})

// 点击标签跳转
function handleTagClick(tag) {
  router.push({ path: tag.path })
}
</script>

<template>
  <div class="tags">
    <el-tag
      v-for="tag in tags"
      :key="tag.path"
      :closable="tag.closable"
      :type="route.name === tag.name ? 'primary' : 'info'"
      @close="() => handleClose(tag)"
      @click="() => handleTagClick(tag)"
      class="tag-item"
      size="large"
    >
      {{ tag.title }}
    </el-tag>
  </div>
</template>
<style lang="scss" scoped>
.tags {
  .tag-item {
    margin-right: 10px;
    cursor: pointer;
  }
}
</style>
